package top.infopub.mgr.cap.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.cap.dao.*;
import top.infopub.mgr.cap.domain.LoanFinDomain;
import top.infopub.mgr.cap.dto.LoanFinDto;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.LoanFinService;
import top.infopub.mgr.cap.vo.LoanFinVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.model.cap.*;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class LoanFinServiceImpl extends GenericServiceImpl<LoanFin, String> implements
		LoanFinService {

	@Autowired
	private LoanFinDao loanFinDao;

	@Autowired
	private LoanFinBankDao loanFinBankDao;

	@Autowired
	private LoanFinDetailDao loanFinDetailDao;

	@Autowired
	private LoanFinAttDao loanFinAttDao;

	@Autowired
    private SetupFinancialDao setupFinancialDao;

	@Autowired
    private ProjectAttachmentDao projectAttachmentDao;

	@Autowired
    private WsFlowProcessService wsFlowProcess;

	@Autowired
    private CapProcessManageService capProcessManageService;

	@Override
	public GenericDao<LoanFin, String> getDao() {
		return loanFinDao;
	}

    @Override
    public Page<LoanFinDomain> selectByDomainWhere(Page<LoanFinDomain> page, LoanFinVo loanFinVo) {
        //处理时间范围
        if (!StringUtils.isEmpty(loanFinVo.getDates())) {
            String[] splitTime = loanFinVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            try {
                loanFinVo.setEndDate(format.parse(splitTime[1]));
                loanFinVo.setStartDate(format.parse(splitTime[0]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<LoanFinDomain>)loanFinDao.selectByDomainWhere(loanFinVo);
    }

    @Override
    public Page<LoanFinDomain> selectMyCheckByDomainWhere(Page<LoanFinDomain> page,
                                                          LoanFinVo loanFinVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<LoanFinDomain>)loanFinDao.selectMyCheckByDomainWhere(loanFinVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveLoanFin(LoanFin loanFin, List<LoanFinDetail> loanFinDetails,
                            List<LoanFinBank> loanFinBanks, List<LoanFinAtt> loanFinAtts) {
        //执行新增
        loanFinDao.insertById(loanFin);

        //批量添加融资合同中金融机构信息
        if(CollectionUtils.isNotEmpty(loanFinBanks)){
            loanFinBankDao.insertByBatch(loanFinBanks);
        }

        //批量添加放款信息
        if(CollectionUtils.isNotEmpty(loanFinDetails)){
            loanFinDetailDao.insertByBatch(loanFinDetails);
        }

        //批量添加附件
        if(CollectionUtils.isNotEmpty(loanFinAtts)){
            loanFinAttDao.insertByBatch(loanFinAtts);
        }

        // 注意 这里根据不同的业务分支判断条件 获得不同enum
        FlowTemplateEnum templateEnum = FlowTemplateEnum.CAP_LOAN_FIN;
        // 处理工作流数据
//        wsFlowProcess.launch(templateEnum, loanFin.getId(), loanFin.getProcessId(), null);
    }

    @Override
    public LoanFinVo selectById(String id){
        return loanFinDao.selectById(id);
    }

    @Override
    public List<LoanFin> queryAll() {
        return loanFinDao.queryAll();
    }

    @Override
    public List<LoanFin> queryAllWithOrg() {
        return loanFinDao.queryAllWithOrg();
    }

    @Override
    public LoanFin selectByProCode(String proCode, String codes) {
        return loanFinDao.selectByProCode(proCode, codes);
    }

    @Override
    public RspVo queryById(String id) {

	    LoanFinDto loanFinDto = new LoanFinDto();
	    //查找主表信息
        LoanFinVo loanFin = loanFinDao.selectById(id);
        loanFinDto.setLoanFinVo(loanFin);
        //根据金融id查找金融信息
       SetupFinancial setupFinancial = setupFinancialDao.selectById(loanFin.getSetupFinancialId());
       loanFinDto.setSetupFinancial(setupFinancial);
       //附件
        //附件
        List<ProjectAttachment> attachmentList = projectAttachmentDao.queryByWhere(loanFin.getProCode(), ProjectFileTypeEnum.FILE_TYPE54.getCode(), null);
        loanFinDto.setFileAtt(fileAttaListToArray(attachmentList));
        return RspVo.getSuccessResponse(loanFinDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo saveAll(AuthorizationVO userDtl, LoanFinVo loanFinVo, SetupFinancial setupFinancial, List<ProjectAttachment> attachmentList, String bodyStr, Integer submitType) {
        LoanFin loanFin1 = new LoanFin();
	    if (StringUtils.isBlank(loanFinVo.getId())){//新增
            BeanUtils.copyProperties(loanFinVo,loanFin1);
            loanFin1.setId(IdFactory.getUUIDUpper());
            loanFin1.setSetupFinancialId(setupFinancial.getId());
            loanFin1.setAddBy(userDtl.getId());
            loanFin1.setAddTime(new Date());
            loanFin1.setLoanStatus("0");
            loanFinDao.insertById(loanFin1);
        }else{//编辑
            LoanFinVo tmpLoanFin = loanFinDao.selectById(loanFinVo.getId());
            if (tmpLoanFin == null) return RspVo.getFailureResponse(400, "融资放款数据不存在~");
            if (StringUtils.isNotBlank(tmpLoanFin.getProcessStatus())
                    && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpLoanFin.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpLoanFin.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
	        loanFin1.setId(loanFinVo.getId());
	        loanFin1.setProCode(loanFinVo.getProCode());
	        loanFin1.setApplyAmount(loanFinVo.getApplyAmount());
	        loanFin1.setAccountDate(loanFinVo.getAccountDate());
	        loanFin1.setOther(loanFinVo.getOther());
	        loanFin1.setSetupFinancialId(setupFinancial.getId());
	        loanFin1.setUptBy(userDtl.getId());
	        loanFin1.setUptTime(new Date());
	        loanFinDao.updateByPrimaryKey(loanFin1);
        }
        if (attachmentList!=null && attachmentList.size()>0){
            //批量插入附件信息
            projectAttachmentDao.deleteByWhere(loanFin1.getProCode(), ProjectFileTypeEnum.FILE_TYPE54.getCode(), null);
            for (ProjectAttachment attachment : attachmentList) {
                attachment.setProCode(loanFin1.getProCode());
            }
            projectAttachmentDao.insertBatch(attachmentList);
        }

        if (submitType==1){
            capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE16, bodyStr, loanFin1.getId(), loanFin1.getProCode(), userDtl);
        }
	    return RspVo.getSuccessResponse(200,"操作成功");
    }

    @Override
    public RspVo financialDetail(String id) {
        SetupFinancial setupFinancial = setupFinancialDao.selectById(id);
        return RspVo.getSuccessResponse(setupFinancial);
    }

    @Override
    @Transactional
    public RspVo modifyFinInfo(LoanFin loanFin, AuthorizationVO vo, String processId) {
	    //修改财务信息
        loanFin.setLoanStatus("1");
        loanFinDao.modifyFinInfo(loanFin);
        //修改流程信息
        CapProcessDetail cpd = capProcessManageService.queryByProcessId(processId);
        LoanFinDto loanFinDto = JSON.parseObject(StringEscapeUtils.unescapeJava(cpd.getDetailJson()), LoanFinDto.class);
        loanFinDto.getLoanFinVo().setActualAmount(loanFin.getActualAmount());
        loanFinDto.getLoanFinVo().setActualDate(loanFin.getActualDate());
        capProcessManageService.modifyDetailJsonById(cpd);
	    return RspVo.getSuccessResponse();
    }

    public String[] fileAttaListToArray(List<ProjectAttachment> list) {
        if (list == null || list.size() <= 0) return null;
        String[] attaArr = new String[list.size()];
        int index = 0;
        for (ProjectAttachment pa : list) {
            StringBuffer tmp = new StringBuffer();
            tmp.append(pa.getSubTypes());
            tmp.append("|");
            tmp.append(pa.getFileName());
            tmp.append(pa.getFileSuffix());
            tmp.append("|");
            tmp.append(IdFactory.getUUIDSerialNumber());
            tmp.append("|");
            tmp.append(pa.getFilePath());
            attaArr[index] = tmp.toString();
            index++;
        }
        return attaArr;
    }
}
